/**
 * calculator
 *
 * @author : tzy
 * @Date : 2021-03-16
 * @Description:
 **/

package com.tang.calculator.symbols;

import com.tang.calculator.context.CalculateContext;
import com.tang.calculator.functions.AbstractFunction;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class RightBracket extends Bracket implements Function {
    @Override
    public int getPriority() {
        return Integer.MIN_VALUE;
    }

    @Override
    public void operate(CalculateContext context) {
        Stack<OperatorSymbol> operatorStack = context.getOperatorStack();
        Stack<ValueSymbol> valueStack = context.getValueStack();

        if (!operatorStack.isEmpty()) {
            while (!operatorStack.isEmpty() && !(operatorStack.peek() instanceof LeftBracket)) {
                OperatorSymbol operator = operatorStack.pop();
                operator.simpleOperate(context);
            }

            OperatorSymbol operatorSymbol = operatorStack.pop();
            if (operatorSymbol instanceof AbstractFunction) {
                AbstractFunction function = (AbstractFunction) operatorSymbol;

                List<ValueSymbol> tempValues = context.getTempValues();
                tempValues.add(valueStack.pop());
                tempValues.removeIf(valueSymbol -> valueSymbol instanceof NullValueSymbol);

                Collections.reverse(tempValues);
                ValueSymbol[] valueSymbols = new ValueSymbol[tempValues.size()];
                tempValues.toArray(valueSymbols);
                function.run(context, valueSymbols);
                context.setTempValues(new LinkedList<>());
            }
        }
    }

    @Override
    public void simpleOperate(CalculateContext context) {

    }

    @Override
    public String getName() {
        return ")";
    }

    /**
     * 校验
     *
     * @param str
     * @return
     */
    @Override
    public boolean check(String str) {
        return false;
    }
}
